<!--存货分类弹窗-->
<template>
    <a-modal :visible="visible" title="存货分类" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel" :width="400" minHeight="500">
        <!-- <a-input-search style="margin-bottom: 8px" placeholder="存货分类名称" @change="onChange" /> -->
        <div style="height: 350px;overflow-y:scroll;">
            <a-tree :tree-data="treeData" :show-line="true" :replaceFields="replaceFields" @select="onTreeSelect" :expandedKeys="expandedKeys" @expand="onExpand" defaultExpandAll :auto-expand-parent="true">

            </a-tree>
        </div>
    </a-modal>
</template>
<script>
import { categoryList } from "@/api/inventory/inventoryClass";
import { classPageListToTree, searchInTreeData } from "@/utils/tree";
let keyMap = new Map();

const x = 3;
const y = 2;
const z = 1;
const treeData = [];


export default {
    props: {
        defaultValut: { // 默认选中项
            type: String,
            default: ''
        }
    },
    data() {
        return {
            visible: false,
            confirmLoading: false,
            treeData, //树形数据
            componentName: '',//输入框字段key

            expandedKeys: [0],//展开指定的树节点
            searchValue: '',
            autoExpandParent: true,//是否自动展开父节点
            dataList: [],//转换成key：value形式


            selectedRowData: [],//树形菜单选中的返回值

            replaceFields: {
                title: "showTitle",
            },
        };
    },
    created() {
        this.getData();
    },
    methods: {
        showModal(code) {
            this.visible = true;
            this.componentName = code;//传递的名字
        },
        handleOk(e) {
            console.log(this.selectedRowData.node.dataRef)
            //提交
            if (this.selectedRowData.node.dataRef.key == '-1' || this.selectedRowData.node.dataRef.key == '') {
                this.$message.error('不是最后一级')
                return;
            } else if (!this.selectedRowData.node.dataRef.isEndNode) {
                this.$message.error('不是最后一级')
                return;
            } else {
                this.confirmLoading = true;
                setTimeout(() => {
                    this.visible = false;
                    this.confirmLoading = false;
                    let array = {
                        id: this.selectedRowData.node.dataRef.id,//物料分类id
                        classCode: this.selectedRowData.node.dataRef.code,//物料分类的编码
                        name: this.selectedRowData.node.dataRef.name,//物料分类名字
                        code: this.componentName,//让父主键知道当前是哪个动态字段
                        backdata:this.selectedRowData.node.dataRef
                    }
                    this.$emit('setValue', array);
                }, 500);
            }
        },
        handleCancel(e) {
            //关闭
            this.visible = false;
        },
        getData() {
            this.treeData = [];
            categoryList().then(response => {
                if (response.code == 200) {
                    const { data } = response;
                    // for (let i = 0; i < response.data.length; i++) {
                    //     const node = response.data[i];
                    //     keyMap.set(node.id, node);
                    // }
                    const childrenNav = [];
                    classPageListToTree(response.data, childrenNav, 0);
                    let showTitleData = this.setTreeData(childrenNav);

                    console.log(showTitleData)

                    this.treeData = [
                        {
                            title: "存货分类",
                            showTitle: "存货分类",
                            key: 0,
                            children: showTitleData
                        }
                    ];
                    showTitleData.forEach(e => {
                        this.expandedKeys.push(e.key)
                    });
                    this.expandedKeys.push(0)
                }
            }).catch(error => { });
        },
        //递归添加显示的tree scopedSlots
        setTreeData(data) {
            for (let i = 0; i < data.length; i++) {
                let element = data[i];
                this.$set(element, "scopedSlots", { title: 'title' });
                this.$set(element, "showTitle", `(${element.code}) ${element.name}`);
                this.$set(element, "key", element.id);
                if (element.children) {
                    this.setTreeData(element.children);
                }
            }
            return data;
        },
        onTreeSelect(keys, row) {
            //树点击
            console.log(keys, row)
            this.selectedRowData = row;
        },
        onExpand(expandedKeys) {
            this.expandedKeys = expandedKeys;
            this.autoExpandParent = false;
        },
        onChange(e) {
            //搜索
            this.generateList(this.treeData);

            const value = e.target.value;
            const expandedKeys = this.dataList.map(item => {
                if (item.title.indexOf(value) > -1) {
                    return this.getParentKey(item.key, this.treeData);
                }
                return null;
            }).filter((item, i, self) => item && self.indexOf(item) === i);
            Object.assign(this, {
                expandedKeys,
                searchValue: value,
                autoExpandParent: true,
            });
        },
        generateList(data) {
            //将tree数组转换成key value形式
            const { dataList } = this;
            for (let i = 0; i < data.length; i++) {
                const node = data[i];
                const key = node.key;
                const title = node.title;
                dataList.push({ key, title: title });
                if (node.children) {
                    this.generateList(node.children);
                }
            }
            Object.assign(this, { dataList })
        },
        getParentKey(key, tree) {
            let parentKey;
            for (let i = 0; i < tree.length; i++) {
                const node = tree[i];
                if (node.children) {
                    if (node.children.some(item => item.key === key)) {
                        parentKey = node.key;
                    } else if (this.getParentKey(key, node.children)) {
                        parentKey = this.getParentKey(key, node.children);
                    }
                }
            }
            return parentKey;
        }
    }
}
</script>
<style lang="less" scoped>
/deep/.ant-tree-title{
    max-width: none !important;
}
</style>